<?php


namespace app\api\controller\User;


use app\api\model\User\UserVipCodeModel;
use app\api\controller\AppController;
use app\api\model\User\UserModel;
use app\Request;
use app\Utils\Util;
use think\App;

class UserVipCode extends AppController
{
    /**
     * @api {get} /get_user_vip_code_list 用户激活码列表
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getUserVipCodeList(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        $where = [
            ['uid', '=', $user['id']]
        ];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        if (empty($page)) {
            $page = 1;
        }
        if (empty($limit)) {
            $limit = 10;
        }

        $list = UserVipCodeModel::getUserVipCodeListWhere($page, $limit, $where);
        $count = UserVipCodeModel::getUserVipCodeCountWhere($where);
        return Util::returnPageJson(self::CODE_SUCCESS, $count, $list, "");
    }

    /**
     * @api {post} /get_activate_vip 激活码激活VIP
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiParam {string} code 激活码
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getActivateVip(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        $code = !empty($param['code']) ? $param['code'] : "";
        $vip_code = UserVipCodeModel::getUserVipCodeWhere([['code','=',$code]]);
        if($user['is_level_type'] == 1 || ($user['level_id'] > 0 && strtotime($user['end_time']) > time())){
            return Util::returnJson(self::CODE_ERROR,null,"你已经是会员了，无需激活");
        }
        if(!empty($vip_code)){
            if($vip_code['status'] != 0){
                return Util::returnJson(self::CODE_ERROR,null,"激活码已使用或已作废");
            }
            $save = [
                'level_id' => 2,
                'end_time' => date("Y-m-d H:i:s",time()+90*86400),
                'is_activate' => 1,
                'up_time' => date("Y-m-d H:i:s",time())
            ];
            $flag = UserModel::updateUserWhere([['id','=',$user['id']]],$save);
            if($flag){
                $code_save = [
                    'status' => 1,
                    'up_time' => date("Y-m-d H:i:s",time())
                ];
                UserVipCodeModel::updateUserVipCodeWhere([['id','=',$vip_code['id']]],$code_save);
                return Util::returnJson(self::CODE_SUCCESS,null,"激活成功");
            }else{
                return Util::returnJson(self::CODE_ERROR,null,"激活失败");
            }
        }else{
            return Util::returnJson(self::CODE_ERROR,null,"无效激活码");
        }
    }

}